package com.bsi.filter;

import com.bsi.properties.PermitAllConfigProperties;
import com.bsi.service.PermissonService;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AuthorizationGlobalFilter
 * @Author LiuSong
 * @Date 2020/7/31 14:46
 * @Version 1.0
 * @Description
 */
@Component
public class AuthorizationGlobalFilter implements GlobalFilter, Ordered {
    private static Logger logger = LogManager.getLogger(AuthorizationGlobalFilter.class);
    @Autowired
    private PermitAllConfigProperties permitAllConfigProperties;
    @Autowired
    private PermissonService permissionService;

    @Autowired
    protected RedisTemplate redisTemplate;

    @Value("${userId}")
    private String TOKEN_USER_ID;

    @Value("${heads.tokenKey}")
    private String HEADS_TOKENKEY;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 首先判断是否放行的url
        String requestURI = request.getURI().getPath();
        if (permitAllConfigProperties.isPermitAllUrl(requestURI)) {
            return response.setComplete();
        }
        String authorization = request.getHeaders().getFirst(HEADS_TOKENKEY);
        //非自定义放行url查看是否存在token 验证是否为jwt token 校验权限 权限不通过返回403
        String userId = null;
        try {
            userId = parseJwtToken(authorization, response);
        } catch (IOException e) {
            e.printStackTrace();
            return response.setComplete();
        }
        // 权限校验（此处根据自己业务扩展）
        boolean checkPermission = permissionService.checkPermisson(userId, requestURI);
        if (!checkPermission) {
            logger.info("userId:{}, requestURI:{} 权限校验不通过", userId, requestURI);
            //权限校验不通过
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        // 校验通过后将userId添加到请求头中
        ServerHttpRequest request1 = request.mutate().header(TOKEN_USER_ID, userId).build();
        ServerWebExchange exchange1 = exchange.mutate().request(request1).build();
        return chain.filter(exchange1);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isJwtBearerToken(String token) {
        return StringUtils.countMatches(token, ".") == 2 && (token.startsWith("Bearer") || token.startsWith("bearer"));
    }

    /**
     * 解析jwtToken令牌
     *
     * @param token
     * @return userId
     */
    private String parseJwtToken(String token, org.springframework.http.server.reactive.ServerHttpResponse servletResponse) throws IOException {
        if (StringUtils.isEmpty(token)) {
            logger.error("当前用户未携带token进行访问");
            servletResponse.setStatusCode(HttpStatus.FORBIDDEN);
            return null;
        }
        boolean jwtBearerToken = isJwtBearerToken(token);
        if (!jwtBearerToken) {
            throw new IllegalArgumentException(token + "此值不为jwt令牌");
        }
        // 去除jwt令牌的头部与签名步
        String jwtBody = StringUtils.substringBetween(token, ".");
        // 获取userId
        String s = new String(Base64.decodeBase64(jwtBody));
        Map map = new com.fasterxml.jackson.databind.ObjectMapper().readValue(s, Map.class);
        return (String) map.get(TOKEN_USER_ID);
    }

}
